# 单例日志实例
import logging
from logging_loki import LokiQueueHandler
from multiprocessing import Queue
from pythonjsonlogger import jsonlogger

# 自定义json格式化键
class CustomJsonFormatter(jsonlogger.JsonFormatter):
  def add_fields(self, log_record, record, message_dict):
    super(CustomJsonFormatter, self).add_fields(log_record, record, message_dict)
    # if not log_record.get('timestamp'):
    #   # this doesn't use record.created, so it is slightly off
    #   now = datetime.now().strftime('%Y-%m-%dT%H:%M:%S.%f')
    #   log_record['timestamp'] = now
    if log_record.get('level'):
      log_record['level'] = log_record['level'].upper()
    else:
      log_record['level'] = record.levelname

# 获取日志实例
def get_app_logger(loki_addr):
  if not hasattr(get_app_logger, "id-photo-service"):
    # fmt = logging.Formatter('%(filename)s-%(lineno)d-%(asctime)s-%(levelname)s-%(message)s')
    formatter = CustomJsonFormatter('%(level)s %(filename)s %(lineno)d %(message)s', json_ensure_ascii=False)

    print("日志服务地址: ", loki_addr)
    # 配置Loki处理器
    loki_handler = LokiQueueHandler(
      Queue(-1),
      url=loki_addr + "/loki/api/v1/push",
      tags={"entry_name": "id-photo-service"},
      # auth=("username", "password"),
      version="1",
    )
    loki_handler.setFormatter(formatter)

    # 配置控制台
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)

    # 初始化实例
    my_logger = logging.getLogger("id-photo-service")
    my_logger.setLevel(logging.INFO)
    # 日志输出到loki
    my_logger.addHandler(loki_handler)
    # 日志输出到控制台
    my_logger.addHandler(console_handler)
    get_app_logger.logger = my_logger

  return get_app_logger.logger
